package com.tiyende.kash.loop.ui.adapter

import android.annotation.SuppressLint
import android.graphics.Color
import android.text.Editable
import android.text.SpannableString
import android.text.Spanned
import android.text.TextWatcher
import android.text.style.ForegroundColorSpan
import android.view.View
import android.view.inputmethod.EditorInfo
import android.view.inputmethod.InputMethodManager
import androidx.appcompat.app.AppCompatActivity
import androidx.recyclerview.widget.DefaultItemAnimator
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.lib.common.adapter.CommonRVVerticalScrollHelper
import com.lib.common.adapter.CommonRecyclerViewAdapter
import com.lib.common.adapter.CommonViewHolderHelper
import com.lib.common.shapeview.layout.ShapeLinearLayout
import com.lib.common.shapeview.layout.ShapeRelativeLayout
import com.tiyende.kash.loop.R
import com.tiyende.kash.loop.configs.TiyendeApiPath
import com.tiyende.kash.loop.configs.TiyendeApiUrl.addCommonParams
import com.tiyende.kash.loop.configs.TiyendeConfigs
import com.tiyende.kash.loop.event.TiyendeEventPointHelper
import com.tiyende.kash.loop.event.TiyendeEventPointType
import com.tiyende.kash.loop.utils.helper.TiyendeCheckParamsHelper
import com.tiyende.kash.loop.utils.shared.TiyendeSharedHelper
import com.tiyende.kash.loop.utils.shared.TiyendeSharedKey
import com.tiyende.kash.loop.weight.font.RobotoMediumEditText
import org.json.JSONObject

/**
 * TiyendeCredit
 * @Author wwdeng
 * @CreateTime: 2024/11/19 13:54
 * @Annotation：认证流程步骤适配器
 */
class TiyendeAuthenticationStepCommonAdapter(recyclerView: RecyclerView?): CommonRecyclerViewAdapter<JSONObject>(recyclerView) {
    override fun getItemViewType(position: Int): Int {
        val model = getItem(position)
        when(model.optString("action")){
            "DATE_PICK",
            "GENDER_PICK",
            "RESIDENCE_TYPE",
            "SELECT_CITY",
            "INDUSTRY_TYPE" ->{//出生日期 || 性别 || 住宅类型 || 城市选择 || 行业类型
                return R.layout.tiyende_authentication_step_common_birthday_item
            }
            "CONTACT_GROUP_RELATION" -> {//联系人关系
                return R.layout.tiyende_authentication_step_contact_relation_item
            }
            "CONTACT_GROUP_PHONE" -> {//联系人电话
                return R.layout.tiyende_authentication_step_contact_mobile_item
            }
            "SELECT" -> {//选择
                return R.layout.tiyende_authentication_step_common_choose_item
            }
            else -> {//输入框
                return R.layout.tiyende_authentication_step_common_input_item
            }
        }
    }

    override fun setItemChildListener(helper: CommonViewHolderHelper, viewType: Int) {
        helper.setItemChildClickListener(R.id.authStepSelect)//选择
        helper.setItemChildClickListener(R.id.authStepContactImage)//选择联系人
        helper.setItemChildClickListener(R.id.authStepMobile)
    }

    override fun fillData(helper: CommonViewHolderHelper, position: Int, model: JSONObject) {
        if (!model.optBoolean("isShowStepItem",true)){
            helper.setVisibility(R.id.stepItemLayout,View.GONE)
            return
        }
        helper.setVisibility(R.id.stepItemLayout,View.VISIBLE)
        //名称
        val authStepTitle = helper.getTextView(R.id.authStepTitle)
        var showTitle = model.optString("title")
        if (TiyendeConfigs.isSwahili()){
            showTitle = model.optString("title_sw")
        }
        authStepTitle.text = findKeywordColor(Color.parseColor("#FFFF3939"),showTitle,"*")

        when(model.optString("action")){
            "DATE_PICK",
            "GENDER_PICK",
            "RESIDENCE_TYPE",
            "SELECT_CITY",
            "INDUSTRY_TYPE" -> {//生日 || 性别 || 住宅类型 || 城市选择 || 行业类型
                showAuthStepBirthdayItemView(helper,position,model)
            }
            "SELECT" ->{//选择
                showAuthStepChooseItemView(helper,position,model)
            }
            "CONTACT_GROUP_RELATION" -> {//联系人关系
                showAuthStepContactRelationItemView(helper,position,model)
            }
            "CONTACT_GROUP_PHONE" -> {//联系人电话
                showAuthStepContactMobileItemView(helper,position,model)
            }
            else -> {//输入框
                showAuthStepInputItemView(helper,position,model)
            }
        }
    }

    /**
     * 输入框类型
     */
    private fun showAuthStepInputItemView(helper: CommonViewHolderHelper, position: Int, model: JSONObject){
        val inputLayout = helper.getView<ShapeLinearLayout>(R.id.authenticationStepInputLayout)
        val imgInput = helper.getImageView(R.id.imgInput)

        //提示语
        val authStepEdit = helper.getView<RobotoMediumEditText>(R.id.authStepEdit)
        var showHint = model.optString("hint")
        if (TiyendeConfigs.isSwahili()){
            showHint = model.optString("hint_sw")
        }
        authStepEdit.setHint(showHint)
        var showText = ""
        if (model.has("selectItem")){
            val selectItem = model.optJSONObject("selectItem")
            selectItem?.let {
                showText = selectItem.optString("title")
            }
        }
        authStepEdit.setText(showText)
        authStepEdit.setInputFocusChangeListener(object : RobotoMediumEditText.IInputFocusChangeListener{
            override fun onFocusChange(v: View?, hasFocus: Boolean) {
                authStepEdit.setTextColor(Color.parseColor("#FFFFFFFF"))
                imgInput.setImageResource(R.mipmap.tiyende_activity_authentication_step_input_icon)
                if (hasFocus){
                    inputLayout.shapeDrawableBuilder
                        .setStrokeColor(Color.parseColor("#FF3ED9AB"))
                        .setSolidColor(Color.parseColor("#FF1F2937"))
                        .intoBackground()
                } else {
                    inputLayout.shapeDrawableBuilder
                        .setStrokeColor(Color.parseColor("#FF334155"))
                        .setSolidColor(Color.parseColor("#FF1F2937"))
                        .intoBackground()
                }
            }
            override fun onCompleteAction(v: View?, content: String, remark: String) {
                var eventType = String.format(TiyendeEventPointType.FORM.TIYENDE_FORM_STEP_INPUT_XX,"${model.optString("stepTitle")}_${model.optString("paramName")}")
                if (model.has("stepType") && model.optString("stepType") == "CONTACT"){
                    eventType = String.format(TiyendeEventPointType.FORM.TIYENDE_FORM_STEP_INPUT_XX,"${model.optString("stepTitle")}_${model.optString("paramName")}_${model.optString("stepItemIndex")}")
                }
                TiyendeEventPointHelper.addEventPointRequestAction(eventType,remark)

                // TODO: panCardNo、ifscCode 失去焦点需要立即校验正确性
                val paramName = model.optString("paramName")
                if (paramName == "panCardNo" || paramName == "ifscCode"){
                    val params = JSONObject().addCommonParams().apply {
                        put("path",TiyendeApiPath.TIYENDE_PATH.TIYENDE_API_CHECK_PARAMS_PATH)
                        put("type",model.optString("stepTitle"))
                        put("param",JSONObject().apply {
                            put(paramName,content)
                        })
                    }
                    TiyendeCheckParamsHelper.onCheckParamsAction(params, callBack = {
                        if (it.contains(paramName)){
                            authStepEdit.setTextColor(Color.parseColor("#FFFF1100"))
                            imgInput.setImageResource(R.mipmap.tiyende_activity_authentication_step_input_error_icon)
                            inputLayout.shapeDrawableBuilder
                                .setStrokeColor(Color.parseColor("#FFFF1E00"))
                                .setSolidColor(Color.parseColor("#FF2D1F1D"))
                                .intoBackground()
                        }
                    })

                }
            }
        })

        authStepEdit.setOnEditorActionListener { v, actionId, event ->
            if (actionId == EditorInfo.IME_ACTION_DONE){
                authStepEdit.clearFocus()
                true
            }
            false
        }
        authStepEdit.addTextChangedListener(object : TextWatcher {
            override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {
            }
            override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
            }
            override fun afterTextChanged(s: Editable?) {
                val obj = JSONObject()
                obj.put("title",s.toString())
                obj.put("value",s.toString())
                model.put("selectItem",obj)
            }
        })
        imgInput.setOnClickListener {
            onShowSoftInput(authStepEdit)
        }
    }

    /* 显示键盘 */
    private fun onShowSoftInput(v: View?) {
        val inputMethodManager = mContext.getSystemService(AppCompatActivity.INPUT_METHOD_SERVICE) as InputMethodManager
        inputMethodManager.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS)
        v?.requestFocus()
    }

    /**
     * 生日 || 性别 || 住宅类型 || 城市选择 || 行业类型
     */
    private fun showAuthStepBirthdayItemView(helper: CommonViewHolderHelper, position: Int, model: JSONObject){
        //提示语
        var showHint = model.optString("hint")
        if (TiyendeConfigs.isSwahili()){
            showHint = model.optString("hint_sw")
        }
        val authStepSelectText = helper.getTextView(R.id.authStepSelectText)
        authStepSelectText.setHint(showHint)
        if (model.has("selectItem")){
            val selectItem = model.getJSONObject("selectItem")
            var showTitle = selectItem.optString("title")
            if (TiyendeConfigs.isSwahili()){
                showTitle = selectItem.optString("title_sw")
            }
            authStepSelectText.text = showTitle
        } else {
            authStepSelectText.text = ""
        }

        val authStepSelectImage = helper.getImageView(R.id.authStepSelectImage)
        authStepSelectImage.setImageResource(R.mipmap.tiyende_activity_authentication_step_select_icon)
    }

    /**
     * 选择类型
     */
    @SuppressLint("NotifyDataSetChanged")
    private fun showAuthStepChooseItemView(helper: CommonViewHolderHelper, position: Int, model: JSONObject){
        val recyclerView = helper.getView<RecyclerView>(R.id.recyclerViewChild)
        val layoutManager = LinearLayoutManager(mContext)
        layoutManager.orientation = RecyclerView.HORIZONTAL
        recyclerView.layoutManager = layoutManager
        val chooseChildAdapter = TiyendeAuthenticationStepChooseChildItemAdapter(recyclerView)
        recyclerView.adapter = chooseChildAdapter
        recyclerView.itemAnimator = DefaultItemAnimator()
        chooseChildAdapter.setOnItemChildClickListener{ _, childView, position ->
            val item = chooseChildAdapter.getItem(position)
            if (item.optBoolean("isSelected",false)){
                return@setOnItemChildClickListener
            }
            //记录上一次选择的类型
            var lastSelectedItem: JSONObject? = null
            chooseChildAdapter.data.forEach {
                if (it.optBoolean("isSelected")){
                    lastSelectedItem = it
                }
                it.put("isSelected",false)
            }
            item.put("isSelected",true)
            model.put("selectItem",item)
            chooseChildAdapter.notifyDataSetChanged()

            //工作信息中，选择No Work时不显示companyCity和industry
            if (model.optString("paramName") == "employmentType"){
                //本次选择为“No Work”需要更新外层适配器
                if (item.optString("value") == "No Work"){
                    for (i in 0..<itemCount){
                        val obj = getItem(i)
                        //选择“No Work” 不显示工作城市和行业性质
                        if (obj.optString("paramName") == "companyCity" || obj.optString("paramName") == "industry"){
                            obj.put("isMust","NO")
                            obj.put("isShowStepItem",false)
                            obj.put("selectItem",null)
                            notifyItemChanged(i)
                        }
                    }
                } else {//本次选择不是“No Work”，需要根据上次选择的类型决定是否需要更新外层适配器
                    lastSelectedItem?.let { lastItem ->
                        //上一次选择的是“No Work”，需要更新外层适配器
                        if (lastItem.optString("value") == "No Work"){
                            for (i in 0..<itemCount){
                                val obj = getItem(i)
                                if (obj.optString("paramName") == "companyCity" || obj.optString("paramName") == "industry"){
                                    obj.put("isMust","YES")
                                    obj.put("isShowStepItem",true)
                                    obj.put("selectItem",null)
                                    notifyItemChanged(i)
                                }
                            }
                        }
                    }
                }
            }

            val subRemark = item.optString("value")
            TiyendeEventPointHelper.addEventPointRequestAction(String.format(TiyendeEventPointType.CLICK.TIYENDE_CLICK_STEP_XX_SELECT,"${model.optString("stepTitle")}_${model.optString("paramName")}"),subRemark)

        }
        val childList = arrayListOf<JSONObject>()
        val dataArray = model.optJSONArray("values")
        if (dataArray != null) {
            for (i in 0..<dataArray.length()) {
                childList.add(dataArray.optJSONObject(i))
            }
        }
        chooseChildAdapter.data = childList
    }

    /**
     * 联系人关系
     */
    @SuppressLint("NotifyDataSetChanged")
    private fun showAuthStepContactRelationItemView(helper: CommonViewHolderHelper, position: Int, model: JSONObject){
        val recyclerView = helper.getView<RecyclerView>(R.id.recyclerViewChild)
        val layoutManager = LinearLayoutManager(mContext)
        layoutManager.orientation = RecyclerView.HORIZONTAL
        recyclerView.layoutManager = layoutManager
        val chooseChildAdapter = TiyendeAuthenticationStepChooseChildItemAdapter(recyclerView)
        recyclerView.adapter = chooseChildAdapter
        recyclerView.itemAnimator = DefaultItemAnimator()
        chooseChildAdapter.setOnItemChildClickListener{ _, _, position ->
            val item = chooseChildAdapter.getItem(position)
            if (item.optBoolean("isSelected",false)){
                return@setOnItemChildClickListener
            }
            chooseChildAdapter.data.forEach {
                it.put("isSelected",false)
            }
            item.put("isSelected",true)
            item.put("position",position)

            var isNotifyDataSetChangedParentAdapter = false
            //判断是否已经选择Other
            if (model.has("selectItem")){
                val selectItem = model.getJSONObject("selectItem")
                if (selectItem.optString("title") == model.optString("relationOtherKey")){
                    selectItem.put("otherValue","")
                    isNotifyDataSetChangedParentAdapter = true
                }
            }
            model.put("selectItem",item)
            chooseChildAdapter.notifyDataSetChanged()
            //上一次选中Other，切换需要刷新 || 本次关系选择Other时才刷新整个Adapter
            if (isNotifyDataSetChangedParentAdapter || item.optString("title") == model.optString("relationOtherKey")){
                notifyDataSetChanged()
            }

            val subRemark = item.optString("value")

            TiyendeEventPointHelper.addEventPointRequestAction(String.format(TiyendeEventPointType.CLICK.TIYENDE_CLICK_STEP_XX_SELECT,"${model.optString("stepTitle")}_${model.optString("paramName")}"),subRemark)
        }
        val childList = arrayListOf<JSONObject>()
        val dataArray = model.optJSONArray("values")
        if (dataArray != null) {
            for (i in 0..<dataArray.length()) {
                childList.add(dataArray.optJSONObject(i))
            }
        }
        chooseChildAdapter.data = childList

        val relationEditLayout = helper.getView<ShapeLinearLayout>(R.id.relationEditLayout)
        val editRelationOther = helper.getView<RobotoMediumEditText>(R.id.editRelationOther)
        editRelationOther.setHint(model.optString("relationOtherHint"))
        relationEditLayout.visibility = View.GONE

        var showOtherValue = ""
        var showTitle = ""
        if (model.has("selectItem")){
            val selectItem = model.getJSONObject("selectItem")
            CommonRVVerticalScrollHelper.newInstance(recyclerView).scrollToPosition(selectItem.optInt("position"))
            showTitle = selectItem.optString("title")
            if (showTitle == model.optString("relationOtherKey")){
                relationEditLayout.visibility = View.VISIBLE
                if (selectItem.has("otherValue")){
                    showOtherValue = selectItem.optString("otherValue","")
                }
            }
        }

        //关系为“Other”时，输入框允许输入
        editRelationOther.isEnabled = showTitle == model.optString("relationOtherKey")
        editRelationOther.setText(showOtherValue)
        editRelationOther.setInputFocusChangeListener(object : RobotoMediumEditText.IInputFocusChangeListener {
            override fun onFocusChange(v: View?, hasFocus: Boolean) {
                if (hasFocus){
                    relationEditLayout.shapeDrawableBuilder
                        .setStrokeColor(Color.parseColor("#FF3ED9AB"))
                        .intoBackground()
                } else {
                    relationEditLayout.shapeDrawableBuilder
                        .setStrokeColor(Color.parseColor("#FF334155"))
                        .intoBackground()
                }
            }
            override fun onCompleteAction(v: View?, content: String, remark: String) {
                var eventType = String.format(TiyendeEventPointType.FORM.TIYENDE_FORM_STEP_INPUT_XX,model.optString("paramName"))
                if (model.has("stepType") && model.optString("stepType") == "CONTACT"){
                    eventType = String.format(TiyendeEventPointType.FORM.TIYENDE_FORM_STEP_INPUT_XX,"${model.optString("stepTitle")}_${model.optString("paramName")}_${model.optString("stepItemIndex")}_Other")
                }
                TiyendeEventPointHelper.addEventPointRequestAction(eventType,remark)
            }
        })
        editRelationOther.setOnEditorActionListener { v, actionId, event ->
            if (actionId == EditorInfo.IME_ACTION_DONE){
                editRelationOther.clearFocus()
                true
            }
            false
        }

        editRelationOther.addTextChangedListener(object : TextWatcher {
            override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {
            }
            override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
            }
            override fun afterTextChanged(s: Editable?) {
                if (model.has("selectItem")){
                    val selectItem = model.getJSONObject("selectItem")
                    selectItem.put("otherValue",s.toString())
                }
            }
        })
    }

    /**
     * 联系电话
     */
    private fun showAuthStepContactMobileItemView(helper: CommonViewHolderHelper, position: Int, model: JSONObject){
        val authStepSelect = helper.getView<ShapeRelativeLayout>(R.id.authStepSelect)
        //提示语
        var showHint = model.optString("hint")
        if (TiyendeConfigs.isSwahili()){
            showHint = model.optString("hint_sw")
        }
        val authStepMobile = helper.getTextView(R.id.authStepMobile)
        authStepMobile.setHint(showHint)
        val authStepMobileEdit = helper.getView<RobotoMediumEditText>(R.id.authStepMobileEdit)
        authStepMobileEdit.setHint(showHint)
        if (model.has("selectItem")){
            val showValue = model.getJSONObject("selectItem").optString("title")
            authStepMobile.text = showValue
            authStepMobileEdit.setText(showValue)
        }
        authStepMobileEdit.setOnEditorActionListener { v, actionId, event ->
            if (actionId == EditorInfo.IME_ACTION_DONE){
                authStepMobileEdit.clearFocus()
                true
            }
            false
        }
        authStepMobileEdit.setInputFocusChangeListener(object : RobotoMediumEditText.IInputFocusChangeListener{
            override fun onFocusChange(v: View?, hasFocus: Boolean) {
                if (hasFocus){
                    authStepSelect.shapeDrawableBuilder
                        .setStrokeColor(Color.parseColor("#FF3ED9AB"))
                        .intoBackground()
                } else {
                    authStepSelect.shapeDrawableBuilder
                        .setStrokeColor(Color.parseColor("#FF334155"))
                        .intoBackground()
                }
            }
            override fun onCompleteAction(v: View?, content: String, remark: String?) {
                var eventType = String.format(TiyendeEventPointType.FORM.TIYENDE_FORM_STEP_INPUT_XX,model.optString("paramName"))
                if (model.has("stepType") && model.optString("stepType") == "CONTACT"){
                    eventType = String.format(TiyendeEventPointType.FORM.TIYENDE_FORM_STEP_INPUT_XX,"${model.optString("stepTitle")}_${model.optString("paramName")}_${model.optString("stepItemIndex")}")
                }
                TiyendeEventPointHelper.addEventPointRequestAction(eventType,remark)
            }
        })
        authStepMobileEdit.addTextChangedListener(object : TextWatcher {
            override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {
            }
            override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
            }
            override fun afterTextChanged(s: Editable?) {
                val obj = JSONObject()
                obj.put("title",s.toString())
                obj.put("value",s.toString())
                model.put("selectItem",obj)
            }
        })

        //是否是审核账号
        val isAdmin = TiyendeSharedHelper.queryTiyendeSharedBoolean(TiyendeSharedKey.TIYENDE_IS_CONFIG_ACCOUNT)
        if(isAdmin){//审核账号 - 允许输入或选择
            authStepMobile.visibility = View.GONE
            authStepMobileEdit.visibility = View.VISIBLE
        } else {//非审核账号只能选择
            //设备是否支持通讯录选择联系人
            if (model.optBoolean("isContactPick")){
                authStepMobile.visibility = View.VISIBLE
                authStepMobileEdit.visibility = View.GONE
            } else {
                authStepMobile.visibility = View.GONE
                authStepMobileEdit.visibility = View.VISIBLE
            }
        }
    }

    private fun findKeywordColor(color: Int, text: String, key: String): SpannableString {
        val spString = SpannableString(text)
        if (!text.contains(key)){
            return spString
        }
        val start = text.indexOf(key)
        val end = start + key.length
        spString.setSpan(ForegroundColorSpan(color), start, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
        return spString
    }
}